package org.example.servicecounselor.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.model.manage.bean.po.security.MyUserDetails;
import org.example.model.manage.bean.po.security.SysPermissions;
import org.example.model.manage.security.SecurityConstants;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(1)
public class GatewayUserAndPermissionFilter implements Filter {

    private final ObjectMapper objectMapper;

    public GatewayUserAndPermissionFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String userId = req.getHeader(SecurityConstants.HEADER_USER_ID);
        String userInfo = req.getHeader(SecurityConstants.HEADER_USER_INFO);
        if (userId == null || userInfo == null) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":401,\"message\":\"未登录\"}");
            return;
        }
        try {
            MyUserDetails details = objectMapper.readValue(userInfo, MyUserDetails.class);
            request.setAttribute(SecurityConstants.ATTR_USER_ID, userId);
            request.setAttribute(SecurityConstants.ATTR_USER_DETAILS, details);
            boolean allowed = details.getPermissions() != null && details.getPermissions().stream()
                    .map(SysPermissions::getAccessName)
                    .anyMatch("counselor"::equals);
            if (!allowed) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write("{\"code\":403,\"message\":\"无权限访问该模块\"}");
                return;
            }
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":401,\"message\":\"用户信息解析失败\"}");
            return;
        }
        chain.doFilter(request, response);
    }
}
